<template>
  <n-config-provider class="w-full h-full" :theme="darkTheme" :theme-overrides="naiveTheme">
    <div v-if="preset?.showName" class="flex w-full py-2">
      <div class="font-bold text-xl">{{ preset?.name || '' }}</div>
      <div class="grow" />
      <n-date-picker v-if="preset?.showTimeSelector" v-model:value="range" type="datetimerange" clearable />
    </div>
    <div :id="'chart' + preset.name" class="rounded-xl w-full h-full" :style="preset.chartStyle" />
  </n-config-provider>
</template>

<script lang="ts">
const defaultPreset: PatternPreset = {
  name: '名字',
  type: 'FLEX_CATALOG_CHART',
  chartParams: [
    { fromColor: warning500, label: '设备数据', flux: '', type: 'line' },
    { fromColor: success500, label: '设备数据2', flux: '', type: 'line' }
  ]
}
</script>

<script lang="ts" setup>
import { naiveTheme } from '../../shared/theme/naive_theme'
import { ref, onMounted, PropType } from 'vue'
import { NConfigProvider, darkTheme, NDatePicker, NButton } from 'naive-ui'
import * as echarts from 'echarts'
import { moment } from 'koagun/lib/utils/moment'
import { secondary500, success500, warning500 } from '../../shared/theme/color'
import { PatternPreset } from '../../shared/utils/pattern'
import { reqExecuteFluxs } from '../../services/device/device.def'
import { axiosReq } from '../../shared/client/axios'
import { composeCatalogCharts } from '../../shared/echart/echart'

const props = defineProps({
  preset: {
    type: Object as PropType<PatternPreset>,
    required: false,
    default: defaultPreset
  }
})

const range = ref<[number, number]>([
  moment().subtract(1, 'd').toDate().getTime(),
  moment().toDate().getTime()
])

onMounted(() => {
  if (!import.meta.env.SSR) refreshData()
})

async function refreshData() {
  const preset: PatternPreset = props.preset
  const start = new Date(range.value[0]).toISOString()
  const stop = new Date(range.value[1]).toISOString()

  const datas = await reqExecuteFluxs(axiosReq, preset.chartParams.map(x => x.flux), start, stop, preset?.bucket)

  const option = composeCatalogCharts(
    datas, preset.chartParams.map(x => x.label), preset.chartParams.map(x => x.fromColor),
    secondary500, preset?.gridX || '6%', preset?.gridY || '10%', { ...preset?.chartOptions }
  )
  const chart = echarts.init(document.getElementById('chart' + preset.name) as any)
  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

</script>

<style>
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
</style>
